<?php
/**
 * Created by PhpStorm.
 * User: DELL
 * Date: 2019/3/4
 * Time: 16:37
 */

namespace app\admin\controller;

use app\admin\model\Admin;
use think\captcha\Captcha;
use think\Controller;
use think\Session;

class Login extends Controller
{
    public function index()
    {
        return $this->fetch();
    }

    public function verify()
    {
        $captcha = new Captcha(['useCurve' => false]);
        return $captcha->entry();
    }

    public function login()
    {
        //获取ajax提交 过来的数据
        $username = input('username');
        $password = input('password');
        $code = input('code');

        //后台验证,如果有一个数据为空，就不合法
        if (empty($username) || empty($password) || empty($code)) {
            $result = [
                'status' => 0,
                'msg' => '提交的数据不合法'
            ];
            return json($result);
        }
        //验证用户输入的验证码是否正确
        $captcha = new Captcha();
        $res = $captcha->check($code);
        if (!$res) {
            return json([
                'status' => 0,
                'msg' => '验证码不正确'
            ]);
        }
        /*
         * 如果验证码验证通过，则验证用户名和密码是否输入正确
         * 1）根据用户名查询数据
         * 2）如果能够查到数据，则再比对密码是否正确
         * 3）如果不能查询到数据，则说明用户名不正确
         * */

        $model = new Admin();
        $where = [
            'username' => $username
        ];
        $node = $model->getOne($where);

        $salt_password = md5(md5($password) . $node['salt']);
        if (is_null($node) == false && $node['password'] == $salt_password) {
            //将用户信息存储与session 中
            Session::set("admin_id", $node['admin_id']);
            Session::set("admin",$node);
            return json([
                'status' => 1,
                'msg' => '登录成功'
            ]);
        } else {
            return json([
                'status' => 0,
                'msg' => '用户名或密码错误'
            ]);
        }
    }
    //退出
    public function logon(){
        //退出 将session中储存的用户信息清理掉
        Session::clear();
        //销毁session
        session_unset();
        $this->redirect("login/index");
    }
}